$(document).ready(function () {
  var table = $('table#table').DataTable({
      initComplete: function(settings, json) {
          $("#table").removeClass('dataTable');
          $("#table").parent().addClass('table-responsive');

          $("#table").parent()
              .css('max-height', $(window).height() - $('#query-area').height() - 260)
              .css('height', 'auto')
              .css('overflow-y', 'visible');

          $("#table").on('change', 'input[type="checkbox"]', function () {
              if($(this).prop('checked')) {
                  $(this).closest('tr').addClass('warning');
              } else {
                  $(this).closest('tr').removeClass('warning');
              }
          });

          // 动态添加搜索条件行间距样式
        $('<style>').text(`#query-area .form-group {margin-bottom: 15px;}`).appendTo('head');

        // 动态添加表头居中样式
        $('<style>').text('#table thead th { text-align: center !important; }').appendTo('head');

        // 添加行点击事件处理
          $("#table tbody").on('click', 'tr', function(e) {
              // 避免点击复选框本身时触发两次
              if (!$(e.target).is('input[type="checkbox"]')) {
                  // 找到当前行的复选框
                  var checkbox = $(this).find('input[type="checkbox"]').first();
                  // 切换复选框状态
                  checkbox.prop('checked', !checkbox.prop('checked'));
                  // 触发change事件以更新行样式
                  checkbox.trigger('change');
              }
          });
      },
    ajax: {
      url: baseUrl + '/datatable',
      data : function(d) {
		var docno    = $('.search-form').find('input[name="documentNumber"]').val();
        var type     = $('.search-form').find('select#type').val();
        var status   = $('.search-form').find('select#status').val();
        //var material = $('.search-form').find('select#material').val();
        var material = $('.search-form').find('input[name="material"]').val();
        var fromdate   = $('.search-form').find('input[name="fromdate"]').val();
        var todate     = $('.search-form').find('input[name="todate"]').val();
        var contnum    = $('.search-form').find('input[name="containernum"]').val();

        d.docno        = docno;
        d.type         = type;
        d.datastatus   = status;
        d.material     = material;
        d.countfmdate  = fromdate;
        d.counttodate  = todate;
        d.containnum   = contnum;
		return d;
      }
    },
    order: [
      [1, 'asc']
    ],
    columns: [{
      data: 'id',
      sortable: false,
      defaultContent: '',
      'class': 'text-center',
      render: function (data, type, row, meta) {
          return '<input type="checkbox" name="ids" value="' + data + '" style="transform: scale(1.5);"/>'
      }

     },{
      name: 'documentNumber',
      data: 'documentNumber'
    },{
      name: 'documentType',
      data: 'documentType',
      render: function (data, type, row, meta) {
      	return VALUES_MAP_DICT_TYPE && VALUES_MAP_DICT_TYPE[data] ? VALUES_MAP_DICT_TYPE[data].text : '';
      }
    },{
      name: 'lineNumber',
      data: 'lineNumber'
    },{
      name: 'materialCode',
      data: 'materialCode'
    },{
      name: 'materialName',
      data: 'materialName'
    },{
      name: 'fromLotattr06',
      data: 'fromLotattr06'
    },{
      name: 'fromLotattr07',
      data: 'fromLotattr07',
        render: function (data, type, row, meta) {
            return data === "*" ? "" : data;
        }
    },{
      name: 'locationCode',
      data: 'locationCode'
    },{
      name: 'containNumber',
      data: 'containNumber'
    },{
      name: 'qtyOrdered',
      data: 'qtyOrdered'
    },{
      name: 'qtyCount',
      data: 'qtyCount'
    },{
      name: 'qtyDiff',
      data: 'qtyDiff'
    },{
      name: 'countTime',
      data: 'countTime'
    },{
      name: 'countBy',
      data: 'countBy'
    },{
      name: 'countMemo',
      data: 'countMemo'
    },{
      name: 'lineStatus',
      data: 'lineStatus',
      render: function (data, type, row, meta) {
            if (data=='0000') return '待盘点';
            if (data=='0200') return '待盘点';
            if (data=='0300') return '已盘点';
            if (data=='0600') return '已核账';
            if (data=='0880') return '已关闭';
        }
    }]
  });

  table.on('click', '.del', function () {
    var id = table.row($(this).parents('tr')).data().id;
    $("#delForm #ids").val(id);
    if (id) {
      bootbox.confirm("确定要删除数据吗?", function (result) {
        if (result) {
          $("#delForm").submit();
        }
      });
    }
  });
  $(".btn.delAll").on("click", function (e) {
    var ids = [];
    $('#table>tbody input:checked').each(function (i, item) {
      ids.push($(item).val());
    });
    $("#delForm #ids").val(ids.join(","));
    if (ids.length > 0) {
      bootbox.confirm("确定要删除选中的数据吗?", function (result) {
        if (result) {
          $("#delForm").submit();
        }
      });
    } else {
      bootbox.alert("请选择要删除的数据.");
    }
  });

  $(".btn.printAll").on("click", function (e) {
      var ids = [];
      $('#table>tbody input:checked').each(function (i, item) {
          ids.push($(item).val());
      });
      $("#printForm #ids").val(ids.join(","));
      if (ids.length > 0) {
          bootbox.confirm("确定要打印的选定的数据吗?", function (result) {
              if (result) {
                  $("#printForm").submit();
              }
          });
      } else {
          bootbox.alert("请选择要打印的数据.");
      }
  });

  $(".btn.closeAll").on("click", function (e) {
    var ids = [];
    $('#table>tbody input:checked').each(function (i, item) {
      ids.push($(item).val());
    });
    $("#closeForm #ids").val(ids.join(","));
    if (ids.length > 0) {
      bootbox.confirm("确定要关闭的数据吗?", function (result) {
        if (result) {
          $("#closeForm").submit();
        }
      });
    } else {
      bootbox.alert("请选择要关闭的数据.");
    }
  });


    $('.form_datetime').datetimepicker({
        format: 'yyyy-mm-dd',
        weekStart: 1,
        autoclose: true,
        startView: 2,
        minView: 2,
        forceParse: false,
        language: 'cn',
        calendarWeeks: true,
        pickerPosition: "bottom-left"
    }).on('changeDate', function (ev) {
        daycount = 0;
        if (null != ev.date && undefined != ev.date) {
            var day = new Date(ev.date.getYear(), ev.date.getMonth(),ev.date.getDate());
            daycount = day.getDate();
        }

    });


  table.on('click', '.enable', function () {
    var that = this;
    var data = table.row($(this).parents('tr')).data();
    var id = data.id;
    var enabled = data.enabled;
    bootbox.confirm("确定要更新选中的数据吗?", function(resul) {
	if (resul) {
	    $.get(baseUrl + "/enable", {
	      enabled: !enabled,
	      ids: id
	    }, function (res) {
	      if (res) {
	        data.enabled = !enabled;
	        $(that).find("i").removeClass("fa-" + (enabled ? "check-" : "") + "square-o").addClass("fa-" + (!enabled ? "check-" : "") + "square-o");
	        toastr.info('操作成功!');
	      }

	    });
	}});
  });


    //导出 动态组织form提交
    $(".btn.export").on("click", function (e) {
        $("#exportForm .param").remove();
        var $frm = $("#exportForm");
        var array = $('.search-form').serializeArray();
        for (i = 0, length = array.length; i < length; i++) {
            key = array[i].name;
            value = array[i].value;
            $frm.append($('<input class="param" type="hidden" name = "' + key + '" value = "' + value + '" />'));
        }
        var params = table.ajax.params();
        $frm.append($('<input class="param" type="hidden" name="input" value = \'' + JSON.stringify(params) + '\' />'));
        $frm.submit();
        // 阻止默认行为
        e.preventDefault();
        return false;
    });


    $('.search-form').on("submit", function (e) {
    table.draw();
    //阻止表单submit
    return false;
  });

});
